# -*- coding: utf-8 -*-

"""
Module implementing MainWindow.
"""

import PyQt4, PyQt4.QtGui, sys 
import tools
import re
import ConfigParser
import os
import string
import codecs

from PyQt4.QtGui import QMainWindow
from PyQt4.QtCore import pyqtSignature

from Ui_HostM import Ui_MainWindow
from Ui_tip import dumpDialog

class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    host_file_path = 'C:\WINDOWS\system32\drivers\etc\hosts'
    user_setting_file_path = 'user_setting.ini'
    
    def __init__(self, parent = None):
         """
         Constructor
         """
         QMainWindow.__init__(self, parent)
         self.setupUi(self)
         
         self.setWindowTitle(u"Host 管理") 
         
         # 隐藏默认设置
         self.label_5.hide()
         self.label_6.hide()
         self.label_7.hide()
         self.label_8.hide()
         user_setting_file_path = self.user_setting_file_path
         cfg=ConfigParser.ConfigParser()
         if cfg.read(user_setting_file_path):
             s=cfg.sections()             #返回所有的section
             if s and 'setting_1' in s:
                 o=cfg.options('setting_1')
                 if o and 'gcn_ip' in o and 'start_flag' in o and 'domain_list' in o and 'end_flag' in o:
                     gcn_ip=cfg.get('setting_1','gcn_ip') #返回字符
                     start_flag=cfg.get('setting_1','start_flag') #返回字符
                     domain_list=cfg.get('setting_1','domain_list') #返回字符
                     end_flag=cfg.get('setting_1','end_flag') #返回字符
                     
                     self.lineEdit_3.setText(gcn_ip)
                     self.lineEdit.setText(start_flag)
                     self.textEdit.setText(domain_list)
                     self.lineEdit_2.setText(end_flag)
    
    @pyqtSignature("")
    def on_pushButton_clicked(self):
        import socket
        tmp = socket.gethostbyname_ex('g.cn')
        if tmp[2]:
            for ip in tmp[2]:
                 self.lineEdit_3.setText(ip)
    
    @pyqtSignature("")
    def on_pushButton_2_clicked(self):
        
         gcn_ip = self.lineEdit_3.text()
         start_flag = self.lineEdit.text()
         domain_list = self.textEdit.document().toPlainText();
         end_flag = self.lineEdit_2.text()
         #print start_flag
         #print domain_list
         #print end_flag
         con = ''
         con += "\n" + start_flag + "\n"
         domain_list_tmp = domain_list.split('&')
         for domain in domain_list_tmp:
             domain = domain.trimmed()
             con += gcn_ip + "\t" + domain + "\n"
         con += end_flag + "\n"
         #print con
         #host_file_path = 'temp.txt'
         host_file_path = self.host_file_path
         file_handler = open(host_file_path,'r+')
         old_host_con = file_handler.read()
         start_flag_tmp=unicode(start_flag)
         end_flag_tmp=unicode(end_flag)
         regex = r"\n"+start_flag_tmp+"\n"+'.*?'+end_flag_tmp+"\n"
         t_list = re.findall(regex, old_host_con , re.S)
         #如果里面已经有了就替换
         if t_list:
             #print t_list
             #print t_list[0]
             result = old_host_con.replace(t_list[0],con)
         else:
             result =  con + "\n" + old_host_con
         try:
             file_handler.close()
             file_handler = open(host_file_path,'w+')
             file_handler.write(result)
             cfg=ConfigParser.ConfigParser()
             h_f = open(self.user_setting_file_path,'w')
             if h_f:
                 cfg=ConfigParser.ConfigParser()
                 #看是否存在该Section，不存在则创建
                 if not cfg.has_section("setting_1"):
                     temp = cfg.add_section("setting_1")
                 #修改一个值，再写回去
                 cfg.set('setting_1','gcn_ip',unicode(gcn_ip))
                 cfg.set('setting_1','start_flag',unicode(start_flag))
                 cfg.set('setting_1','domain_list',domain_list)
                 cfg.set('setting_1','end_flag',unicode(end_flag))
                 cfg.write(h_f)
                 dialog=dumpDialog(self)
                 dialog.set_tip(u'恭喜设置成功')
                 dialog.setUI(self)
                 dialog.show()
             
             #file_handler.close()
         finally:
             file_handler.close()
             print 'over'
     
    @pyqtSignature("")
    def on_pushButton_3_clicked(self):
         #重置按钮
         def_gcn_ip = self.label_8.text()
         def_start_flag = self.label_6.text()
         def_domain_list = self.label_5.text();
         def_end_flag = self.label_7.text()
         
         self.lineEdit_3.setText(def_gcn_ip)
         self.lineEdit.setText(def_start_flag)
         self.textEdit.setText(def_domain_list)
         self.lineEdit_2.setText(def_end_flag)

if __name__ == "__main__":   
     app = PyQt4.QtGui.QApplication(sys.argv)   
     dlg = MainWindow()   
     dlg.show()   
     sys.exit(app.exec_())
